package nc.bs.yht.Servlet;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.adaptor.IHttpServletAdaptor;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.framework.server.ISecurityTokenCallback;
import nc.bs.itf.hopg.IYhtToHOPGService;
import nc.vo.pub.BusinessException;
import ncc.bs.utils.GetParamConfigUtil;
import ncc.bs.utils.GloableConfigParam;
import ncc.bs.utils.ResultMessage;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

public class YhtPullHOPGYSSDataService extends HttpServlet implements IHttpServletAdaptor {
    public IYhtToHOPGService yhtToHOPGService;
    public BaseDAO baseDAO;
    @Override
    public void doAction(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter pw = null;
        String result = "";
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        pw = resp.getWriter();
        try {
            NCLocator.getInstance().lookup(ISecurityTokenCallback.class).token("NCSystem".getBytes(),"pfxx".getBytes());
            InvocationInfoProxy.getInstance().setUserDataSource("bip");
            JSONObject json = this.getRequestParam(req);
            this.checkParam(json);
            List<Map<String, Object>> lists = this.getYhtToHOPGService().getHOPGYSDataByName(json);
            JSONArray data = new JSONArray();
            String message = "";
            if (lists.isEmpty()) {
                message = "查无数据!";
            }else{
                message = "查询成功!";
                ObjectMapper objMapper = new ObjectMapper();
                String userValue = objMapper.writeValueAsString(lists);
                data = JSONArray.parseArray(userValue);
            }
            result = ResultMessage.success(data, message).toJSONString();

        } catch (Exception e) {
            result = ResultMessage.error(e.getMessage(), e).toJSONString();
        }
//        pw.println(result);
        pw.write(result);
        pw.flush();
        return;
    }

    /**
     * 获取请求参数
     * @param req
     * @return
     */
    private JSONObject getRequestParam(HttpServletRequest req) throws BusinessException {
        InputStream is = null;
        ByteArrayOutputStream byteOut = null;
        JSONObject param = new JSONObject();
        try{
            is = new BufferedInputStream(req.getInputStream());
            byteOut = new ByteArrayOutputStream();
            int b = 0;
            while((b = is.read()) != -1) {
                byteOut.write(b);
            }
            byte[] temp = byteOut.toByteArray();
            String json = new String(temp, "UTF-8");
            if("".equals(json) || json == null) {
                throw new BusinessException("请求参数不允许为空!");
            }
            param = JSONObject.parseObject(json);
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }finally {
            if(byteOut != null) {
                try {
                    byteOut.close();
                } catch (Exception e) {
                    throw new BusinessException("输入流关闭异常:" + e.getMessage());
                }
            }
            if(is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                    throw new BusinessException("字节输出流关闭异常:" + e.getMessage());
                }
            }
        }
        return param;
    }

    /**
     * 检查请求参数
     * @param json
     * @throws BusinessException
     */
    private void checkParam(JSONObject json) throws BusinessException{
        StringBuilder error = new StringBuilder();
        if("".equals(json.getString("orgName")) || json.getString("orgName") == null) {
            error.append("组织 不允许为空, ");
        }
        if(error.toString().length() > 0 ) throw new BusinessException(error.toString());
    }


    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.CorsConfig(req, resp);
        doAction(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.CorsConfig(req, resp);
        doAction(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.CorsConfig(req, resp);
        doAction(req, resp);
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.CorsConfig(req, resp);
        doAction(req, resp);
    }
    /**
     * 处理跨越问题
     * @param req
     * @param resp
     */
    private void CorsConfig (HttpServletRequest req, HttpServletResponse resp) {// 设置跨域响应头
        resp.setHeader("Access-Control-Allow-Origin", "*"); // 生产环境建议替换为具体域名
        resp.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
        resp.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setHeader("Access-Control-Max-Age", "3600");
        if ("OPTIONS".equalsIgnoreCase(req.getMethod())) {
            resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
            return;
        }
    }


    public IYhtToHOPGService getYhtToHOPGService() {
        if (this.yhtToHOPGService == null) {
            this.yhtToHOPGService = NCLocator.getInstance().lookup(IYhtToHOPGService.class);
        }
        return yhtToHOPGService;
    }
}
